const mysql = require("mysql");
const { mysqlConfig } = require("../config/index");
const pool = mysql.createPool(mysqlConfig);
const { logger } = require("../logs/index");

//数据库查询方法
exports.query = (sql) => {
  return new Promise((resovle, reject) => {
    pool.getConnection((err, connection) => {
      if (err) {
        logger.error(err);
        return;
      }
      console.log("数据库连接成功");
      connection.query(sql, function (err, result) {
        connection.release();
        if (err) {
          console.error(err);
          logger.error(err);
          resovle();
          return;
        }
        resovle(result);
      });
    });
  });
};

//数据库插入方法
exports.insert = (sql, data) => {
  return new Promise((resovle, reject) => {
    pool.getConnection((err, connection) => {
      if (err) {
        logger.error(err);
        return;
      }
      console.log("数据库连接成功");
      connection.query(sql, data, function (err, result) {
        connection.release();
        if (err) {
          console.log(err);
          logger.error(err);
          return;
        }
        resovle(result);
      });
    });
  });
};
